package util;

import org.junit.platform.commons.util.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName hexoUtil
 * @description: 替换七牛云图床的链接，操作markdown文档
 * @author: 荣燊
 * @create: 2022-04-12 16:04
 **/
public class HexoUtil {

    /**
     * 将markdown中的图片地址取出
     *
     * @param markdown markdown内容
     */
    public static List<String> getMatchList(String markdown) {
        List<String> imagePrefixList = Stream.of(".jpg", ".bmp", ".gif", ".ico", ".pcx", ".jpeg", ".tif", ".png").
                collect(Collectors.toList());
        System.out.println("读取到imagePrefixList的数组大小："+imagePrefixList.size());
        ArrayList<String> result = new ArrayList<>();
        String[] split = markdown.split("\\!\\[Description\\]\\(");
        for (String imgUrl : split) {
            if (StringUtils.isNotBlank(imgUrl) && (imgUrl.startsWith("http://") || imgUrl.startsWith("https://"))) {
                imagePrefixList.stream().filter(imagePrefix -> imgUrl.contains(imagePrefix)).forEach(imagePrefix -> result.add(imgUrl.substring(0, imgUrl.lastIndexOf(imagePrefix) + imagePrefix.length())));
            }
        }
        //
        System.out.println("");
        return result;
    }

    /**
     * 替换内容中的图片语法值
     *
     * @param markdown
     */
    public static String repUrl(String markdown) {
        String[] split = markdown.split("\\!\\[Description\\]\\(");
        for (String imgUrl : split) {
            if (StringUtils.isNotBlank(imgUrl) && (imgUrl.startsWith("http://") || imgUrl.startsWith("https://"))) {
                System.out.println("图片路径---------："+imgUrl);
                markdown = markdown.replace("![Description](" + imgUrl.substring(0, imgUrl.lastIndexOf(")")) + ")", "");
            }
        }
        return markdown;
    }

    public static void main(String[] args) throws IOException {
        StringBuffer buffer = new StringBuffer();
        BufferedReader bf= new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\testMarkdown\\《一秒钟》.md"));
        String s = null;
        while((s = bf.readLine())!=null){//使用readLine方法，一次读一行
            buffer.append(s.trim());
        }
        String xml = buffer.toString();
        //
        System.out.println("该文件中字符串的数量为："+xml.length());
        // 开始查找图片链接
        List<String> matchList = getMatchList(xml);
        for (String s1 : matchList) {
            System.out.println(s1);
        }
    }

}
